package com.sadam.ui4.FragmentHomePage;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;

import java.util.ArrayList;
import java.util.List;
/**
 * VideoAdapter 类：继承自 RecyclerView.Adapter，是 RecyclerView 的适配器。
 * 负责将 Video 数据列表绑定到 item 视图上，控制列表的显示逻辑（如创建 ViewHolder、绑定数据等）。
 * 它是连接数据（Video）与 UI（RecyclerView）的桥梁。
 */

public class VideoAdapter extends RecyclerView.Adapter<VideoViewHolder> {
    private List<Video> videos = new ArrayList<>();// 存储要显示的视频数据列表
    private MainActivity mainActivity;
    private MySqLiteOpenHelper dbHelper;

    public VideoAdapter(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
    }
    public VideoAdapter(MainActivity mainActivity, MySqLiteOpenHelper dbHelper) {
        this.mainActivity = mainActivity;
        this.dbHelper = dbHelper;
    }

    public List<Video> getVideos() {
        return videos;
    }

    public void setVideos(List<Video> videos) {
        this.videos = videos;
        this.notifyDataSetChanged();
    }
    @Override
    public void onViewRecycled(@NonNull VideoViewHolder holder) {
        super.onViewRecycled(holder);
        holder.release(); // 释放 MediaPlayer
    }
    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_recycler_view_item_layout, parent, false);
        VideoViewHolder videoViewHolder = new VideoViewHolder(view);

        int count_of_item_show_on_one_screen = 1;//一个屏幕能显示的item 数目
        int parentHeight = parent.getHeight();
        parent.getWidth();
        ViewGroup.LayoutParams layoutParams = videoViewHolder.itemView.getLayoutParams();
        layoutParams.height = (parentHeight / count_of_item_show_on_one_screen);

        return videoViewHolder;
    }


    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        Video video = videos.get(position);

        // 获取当前登录用户
        User currentUser = User.getCurrentUser(mainActivity, dbHelper);
        if (currentUser == null) {
            // 未登录，跳转到登录页或提示
            Toast.makeText(mainActivity, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 将数据传给 ViewHolder
        holder.bind(video, dbHelper, currentUser);
    }

    @Override
    public int getItemCount() {
        return videos.size();
    }
}